package com.example.administrator.myapplication;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import cn.jpush.android.api.JPushInterface;


public class MainActivity extends AppCompatActivity {
    private EditText mEditText1,mEditText2;
    private Button mButton;
    private TextView mTextView;
    private Handler mHandler;
    String username;
    String password;
    private String access_token;
   private Context context=null;


    /*Map<String,String> map=new HashMap<>();*/


    /*private String recall="";*/
    public void send(){
/*
* 请求网络连接
*
* */
    String ff="";
        String target;
        target="http://soymilk.nfc100.cn/api/auth/login";
               /* http://soymilk.nfc100.cn/api/order/my-order?num=5*/
        try {
            URL url=new URL(target);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            connection.setDoOutput(true);


            String data="mobile="+username+"&password="+ password;

            connection.getOutputStream().write(data.getBytes());
            int code=connection.getResponseCode();



if (code==200){
    /*connection.setDoOutput(true);*/
    InputStream inputStream=connection.getInputStream();
    ByteArrayOutputStream bw=new ByteArrayOutputStream();

    int length=-1;
    byte[] buffer=new byte[1024];
    while ((length=inputStream.read(buffer))!=-1){

        bw.write(buffer,0,length);
    }
    if (inputStream!=null){
        ff=bw.toString();
        Message message=new Message();
        message.obj=ff;
        inputStream.close();
        mHandler.sendMessage(message);
    }

        connection.disconnect();



}





           /* String string=stringBuffer.toString();*/


/*
            BufferedReader bufferedReader=new BufferedReader(reader);
            String putline=null;
            while ((putline=bufferedReader.readLine())!=null){
                target+=putline;

            }*/
       /*     Message message=new Message();
            message.obj=recall;
            reader.close();
            connection.disconnect();
*/

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SharedPreferences sp=getSharedPreferences("data",0);
        String access_token=sp.getString("access_token",null);
        String mobile=sp.getString("mobile",null);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        JPushInterface.setAlias(this,0,mobile);
        if (access_token!=null){
            Intent intent=new Intent(MainActivity.this,Shouye.class);
            startActivity(intent);

        }






        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        initview();

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {

   if (!isNetworkConnect(MainActivity.this)){
       AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
       builder.setTitle("Warning!");
   builder.setMessage("请连接网络");
       builder.setPositiveButton("网络连接", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {


               startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

           }






       });
       builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();

           }
       }).show();



   }

                username=mEditText1.getText().toString();
                password=mEditText2.getText().toString();



/*
*
* 数据不可 粘贴 复制
* */            mEditText2.setLongClickable(false);
                mEditText2.setTextIsSelectable(false);
                mEditText2.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

                mEditText2.setCustomSelectionActionModeCallback(new AbsListView.MultiChoiceModeListener() {
                    @Override
                    public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {

                    }

                    @Override
                    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                        return false;
                    }

                    @Override
                    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                        return false;
                    }

                    @Override
                    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                        return false;
                    }

                    @Override
                    public void onDestroyActionMode(ActionMode mode) {

                    }});

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        send();
                    }
                }).start();
            }
        });
        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String r= (String) msg.obj;
                    JsonContect(r);
                super.handleMessage(msg);


            }
        };


    }
    public void JsonContect(String r){
/*
* Json数据解析
* */
        try {
            JSONObject jsonObject=new JSONObject(r);
            int error=jsonObject.getInt("error");
            String message=jsonObject.getString("message");
            if (error==0){
                JSONObject data=jsonObject.getJSONObject("data");
                String access_token=data.getString("access_token");
                String partner_name=data.getString("partner_name");
                int first_login=data.getInt("first_login");
                int  role_id=data.getInt("role_id");
                String mobile =data.getString("mobile");

                SharedPreferences sh=getSharedPreferences("data",0) ;
                    SharedPreferences.Editor editor=sh.edit();
                    editor.putString("access_token",access_token);
                    editor.putString("partner_name",partner_name);
                 editor.putInt("first_login",first_login);
                editor.putInt("role_id",role_id);
                editor.putString("mobile",mobile);

                editor.commit();
               /* InitData();*/

                Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();
                Intent mintent=new Intent(MainActivity.this,Shouye.class);
                startActivity(mintent);
  finish();

            }
            else if (error==5){
                mEditText2.setText("");
                mEditText2.requestFocus();
                Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();
            }
            else if (error==12){

                mEditText2.setText("");
                mEditText2.requestFocus();
                Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();

            }
            else if (error==10){

                mEditText2.setText("");
                mEditText2.requestFocus();
                Toast.makeText(MainActivity.this,message,Toast.LENGTH_SHORT).show();

            }
            else if (error==4){





            }






           // String s=error+message+access_token+partner_name+first_login+role_id+mobile;

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }






public boolean isNetworkConnect(Context context){
        if (context!=null){
            ConnectivityManager manager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo=manager.getActiveNetworkInfo();
            if (networkInfo!=null){

                networkInfo.isConnected();
                return true;

            }


        }

    return false;
}



    private void initview() {
        mButton=findViewById(R.id.bt1);
        mTextView=findViewById(R.id.tv1);
        mEditText1=findViewById(R.id.ed1);
        mEditText2=findViewById(R.id.ed2);
    }
}
